package com.example.auv_660.moduleload;

import com.example.auv_660.MainActivity;
import com.example.auv_660.network.tcp.ModuleReadHandler;
import com.example.auv_660.network.tcp.ModuleWriteHandler;
import com.example.auv_660.util.Constants;
import com.example.auv_660.util.MsgType;
import com.example.auv_660.util.ThreadPool;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.util.TimerTask;

public class BatteryLoad extends ModuleLoad {
    private static final String BATTERY_TIME_TASK = "$Ask,Battery*\r\n";
    private ModuleWriteHandler batteryWriteHandler;
    private ModuleReadHandler batteryReadHandler;
    private int threadKey;
    private AsynchronousSocketChannel asynchronousSocketChannel;
    private MainActivity mainActivity = MainActivity.getInstance();
    private String batteryValue;

    public BatteryLoad() throws IOException
    {

    }

    @Override
    public void doModuleLoad(final String remoteModuleIP, final AsynchronousSocketChannel asynchronousSocketChannel) {
        if (remoteModuleIP.equals(Constants.BATTER_IP))
        {
            if (this.asynchronousSocketChannel != null)
            {
                releaseModuleResource();
            }

            this.asynchronousSocketChannel = asynchronousSocketChannel;

            if (batteryWriteHandler == null)
            {
                batteryWriteHandler = new ModuleWriteHandler(asynchronousSocketChannel);
            }

            if (batteryReadHandler == null)
            {
                batteryReadHandler = new ModuleReadHandler(asynchronousSocketChannel)
                {
                    @Override
                    public void completed(Integer result, ByteBuffer attachment)
                    {
                        if (result > 0)
                        {
                            attachment.flip();
                            byte[] bytes = new byte[attachment.remaining()];
                            attachment.get(bytes);
                            String str = new String(bytes);

                            batteryValue = str.split("\\*")[0].split("\\,")[2];

                            if (mainActivity != null && !batteryValue.contains("no"))
                            {
                                mainActivity.sendMsgToMainThread(MsgType.BATTERY_MSG, batteryValue + "%");
                            }
                            else
                            {
                                mainActivity.sendMsgToMainThread(MsgType.BATTERY_MSG, "等待电量反馈");
                            }
                            getMessageFromModule();
                        }
                    }
                };
                batteryReadHandler.getMessageFromModule();
            }

            try
            {
                if (mainActivity != null && asynchronousSocketChannel != null)
                {
                    mainActivity.sendMsgToMainThread(MsgType.BATTERY_CONN,
                            asynchronousSocketChannel.getRemoteAddress().toString().split("/")[1]);
                }
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }

            if (batteryWriteHandler == null)
            {
                if (mainActivity != null)
                {
                    mainActivity.sendMsgToMainThread(MsgType.BATTERY_CONN, "失去连接");
                }
            }
            else
            {
                if (threadKey != 0)
                {
                    ThreadPool.INSTANCE.getThreadPoolProxy().shutDownScheduledTask(threadKey);
                }

                threadKey = ThreadPool.INSTANCE.getThreadPoolProxy().scheduledTask(new TimerTask() {
                    @Override
                    public void run() {
                        batteryWriteHandler.sendCommandToModule(BATTERY_TIME_TASK);
                    }
                }, 1000);
            }

            return;
        }
        else
        {
            ModuleLoad nextModule = this.getNextModule();
            if (nextModule != null)
            {
                nextModule.doModuleLoad(remoteModuleIP, asynchronousSocketChannel);
            }
        }
    }

    @Override
    public ModuleWriteHandler getWriterHandler() {
        if (batteryWriteHandler == null)
        {
            if (mainActivity != null)
            {
//                mainActivity.sendMsgToMainThread(MsgType.TOAST_MSG, "电源模块未连接");
            }
        }
        return batteryWriteHandler;
    }

    @Override
    public ModuleReadHandler getReadHandler() {
        if (batteryReadHandler == null)
        {
            if (mainActivity != null)
            {
//                mainActivity.sendMsgToMainThread(MsgType.TOAST_MSG, "电源模块未连接");
            }
        }
        return batteryReadHandler;
    }

    @Override
    public void releaseModuleResource() {
        ThreadPool.INSTANCE.getThreadPoolProxy().shutDownScheduledTask(threadKey);

        if (this.asynchronousSocketChannel != null)
        {
            try
            {
                this.asynchronousSocketChannel.close();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
        if (batteryWriteHandler != null)
        {
            batteryWriteHandler = null;
        }
        if (batteryReadHandler != null)
        {
            batteryReadHandler = null;
        }
    }

    public String getBatteryValue()
    {
        if (batteryValue != null && !batteryValue.contains("no"))
        {
            return (batteryValue + "%");
        }
        else
        {
            return "暂无电量显示";
        }
    }
}
